import os
import sys
from multiprocessing import Process, Queue

sys.path.append(os.path.abspath("."))


def kwargs_to_cmd(kwargs):
    cmd = "python main_nlp.py "
    for flag, val in kwargs.items():
        cmd += f"--{flag}={val} "

    return cmd


def run_exp(gpu_num, in_queue):
    while not in_queue.empty():
        try:
            experiment = in_queue.get(timeout=3)
        except:
            return

        experiment["multigpu"] = gpu_num
        print(f"==> Starting experiment {kwargs_to_cmd(experiment)}")
        os.system(kwargs_to_cmd(experiment))


def main():
    dataset = 'conll03'
    log_dir = f"./runs/{dataset}"

    methods = [
        # 'dense',
        # 'supsup',
        'wm',
        # 'sswarmup',
        # 'ss'
    ]
    # seeds = range(0, 5) # seeds 需要设置的参数

    experiments = []

    seed = 0

    # 对参数调整，默认参数保存不变
    # alphas = [0.00008,0.00004,0.00001,
    #           0.000008,0.000004,0.000001,
    #           0.0000008,0.0000004,0.0000001,
    #           0.00000008,0.00000004,0.00000001,
    #           0.000000008,0.000000004,0.000000001] #### 0.00000004
    for method in methods:
        config_fn = f'./experiments/config_{dataset}_{method}.yaml'
        kwargs = {
            "config": config_fn,
            "exp_name": f"{method}~seed={seed}",
            "seed": seed,
            "log-dir": log_dir,
        }
        experiments.append(kwargs)


    queue = Queue()
    for e in experiments:
        queue.put(e)

    processes = []
    gpus = [0]
    for gpu in gpus:
        p = Process(target=run_exp, args=(gpu, queue))
        p.start()
        processes.append(p)

    for p in processes:
        p.join()


if __name__ == "__main__":
    main()